package or.exa.cangguan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import or.exa.cangguan.utils.OrderUtil;
import or.exa.cangguan.common.Page;
import or.exa.cangguan.common.Redis;
import or.exa.cangguan.entity.dto.EmployeeDto;
import or.exa.cangguan.entity.po.Employee;
import or.exa.cangguan.entity.vo.EmployeeVo;
import or.exa.cangguan.mapper.EmployeeMapper;
import or.exa.cangguan.mapper.StoreMapper;
import or.exa.cangguan.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderUtil orderUtil;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private Redis redis;



    //新增员工
    @Override
    public int addEmployee(EmployeeVo employeeVo) {
        Date date = new Date(System.currentTimeMillis());


        Employee employee = new Employee();
        BeanUtil.copyProperties(employeeVo,employee);
        employee.setEmployeeCode(orderUtil.generateOrderNo("E"));

        employee.setCreateBy(0);
        employee.setCreateTime(date);
        employee.setUpdateBy(0);
        employee.setUpdateTime(date);
        redis.del("employeeName");


        return employeeMapper.insert(employee);
    }


    // 删除员工
    @Override
    public int deleteEmployee(String eployeeCode) {
        int i = employeeMapper.deleteByPrimaryKey(eployeeCode);
        redis.del("employeeName");

        return i;
    }



    @Override
    public int updateEmployee(EmployeeVo employeeVo) {
        Employee employee = new Employee();

        Date date = new Date(System.currentTimeMillis());
        employee.setUpdateBy(0);
        employee.setUpdateTime(date);

        BeanUtil.copyProperties(employeeVo,employee);
        int i = employeeMapper.updateByPrimaryKeySelective(employee);
        redis.del("employeeName");


        return i;
    }


    //查询员工
    @Override
    public Page selectEmployee(EmployeeVo employeeVo) {
        Page page = new Page();
        BeanUtil.copyProperties(employeeVo,page);
        int totalNum=employeeMapper.selectEmployeeCount(employeeVo);
        page.setTotalNum(totalNum);
        List<EmployeeDto> employeeDtos = employeeMapper.selectEmployee(employeeVo,page);
        page.setResultList(employeeDtos);

        return page;
    }


    //查询所有员工名
    @Override
    public List<String> selectName() {

        if (redis.idExists("employeeName")){
            return (List<String>) redis.get("employeeName");
        }
        else {
            List<String> employeeName = employeeMapper.selectName();
            redis.set("employeeName", employeeName);
            return employeeName;
        }

    }
}
